<template>
    <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}产线`">
        <el-form ref="ruleFormRef" label-width="120px" label-suffix=" :" :rules="rules" :disabled="drawerProps.isView"
            :model="drawerProps.row" :hide-required-asterisk="drawerProps.isView">
            <el-form-item label="产线编码" prop="lineCode" v-if="drawerProps.title === '新增'">
                <el-input v-model="drawerProps.row.lineCode" placeholder="请输入唯一产线编码" clearable maxlength="50" show-word-limit />
            </el-form-item>

            <el-form-item label="产线名称" prop="lineName">
                <el-input v-model="drawerProps.row.lineName" placeholder="请输入产线名称" clearable maxlength="100" show-word-limit />
            </el-form-item>

            <el-form-item label="所属工厂" prop="factoryId">
                <el-select v-model="drawerProps.row.factoryId" placeholder="请选择工厂" clearable style="width: 100%" @change="handleFactoryChange">
                    <el-option v-for="factory in factoryList" :key="factory.id" :label="factory.factoryName" :value="factory.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="所属车间" prop="workshopId">
                <el-select v-model="drawerProps.row.workshopId" placeholder="请选择车间" clearable style="width: 100%" :disabled="!drawerProps.row.factoryId">
                    <el-option v-for="workshop in workshopList" :key="workshop.id" :label="workshop.workshopName" :value="workshop.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="产线类型" prop="lineType">
                <el-select v-model="drawerProps.row.lineType" placeholder="请选择产线类型" clearable style="width: 100%">
                    <el-option label="装配线" value="ASSEMBLY" />
                    <el-option label="测试线" value="TESTING" />
                    <el-option label="包装线" value="PACKAGING" />
                    <el-option label="检验线" value="INSPECTION" />
                </el-select>
            </el-form-item>


            <el-form-item label="最大设备数" prop="maxDeviceCapacity">
                <el-input-number v-model="drawerProps.row.maxDeviceCapacity" :min="1" :max="999" placeholder="请输入最大设备容量" style="width: 100%" />
            </el-form-item>

            <el-form-item label="位置" prop="location" v-if="drawerProps.isView">
                <el-input v-model="computedLocation" disabled style="width: 100%" />
            </el-form-item>


            <el-form-item label="描述" prop="description">
                <el-input v-model="drawerProps.row.description" type="textarea" :rows="3" placeholder="请输入产线描述" clearable maxlength="500" show-word-limit />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </el-drawer>
</template>

<script setup lang="ts" name="ProductionLineDrawer">
import { ref, reactive, computed, watch } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import type { ProductionLine } from "@/api/modules/productionLine";
import { getEnabledFactoryList, getEnabledWorkshopsByFactoryId } from "@/api/modules/productionLine";

// 抽屉属性接口
interface DrawerProps {
    title: string;
    isView: boolean;
    row: Partial<ProductionLine.ProductionLineListItem>;
    api?: (params: any) => Promise<any>;
    getTableList?: () => void;
}

// 工厂和车间数据
const factoryList = ref<{ id: string; factoryName: string }[]>([]);
const workshopList = ref<{ id: string; workshopName: string }[]>([]);

// 表单验证规则
const rules = reactive({
    lineCode: [
        { required: true, message: "产线编码不能为空" },
        { max: 50, message: "长度不能超过50个字符" }
    ],
    lineName: [
        { required: true, message: "产线名称不能为空" },
        { max: 100, message: "长度不能超过100个字符" }
    ],
    factoryId: [
        { required: true, message: "请选择所属工厂" }
    ],
    workshopId: [
        { required: true, message: "请选择所属车间" }
    ],
    lineType: [
        { required: true, message: "请选择产线类型" }
    ],
    supportedProductTypes: [
        { max: 500, message: "长度不能超过500个字符" }
    ],
    description: [
        { max: 500, message: "长度不能超过500个字符" }
    ]
});

// 抽屉可见性
const drawerVisible = ref(false);

// 抽屉属性
const drawerProps = ref<DrawerProps>({
    isView: false,
    title: "",
    row: {}
});

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 计算位置信息
const computedLocation = computed(() => {
    const factory = factoryList.value.find(f => f.id === drawerProps.value.row.factoryId);
    const workshop = workshopList.value.find(w => w.id === drawerProps.value.row.workshopId);
    const factoryName = factory?.factoryName || drawerProps.value.row.factoryName || '';
    const workshopName = workshop?.workshopName || drawerProps.value.row.workshopName || '';
    const lineName = drawerProps.value.row.lineName || '';
    
    if (factoryName && workshopName && lineName) {
        return `${factoryName}-${workshopName}-${lineName}`;
    }
    return drawerProps.value.row.location || '';
});

// 获取工厂列表
const loadFactoryList = async () => {
    try {
        const res = await getEnabledFactoryList();
        factoryList.value = res.data || [];
    } catch (error) {
        console.error('获取工厂列表失败:', error);
    }
};

// 获取车间列表
const loadWorkshopList = async (factoryId: string) => {
    try {
        const res = await getEnabledWorkshopsByFactoryId(factoryId);
        workshopList.value = res.data || [];
    } catch (error) {
        console.error('获取车间列表失败:', error);
        workshopList.value = [];
    }
};

// 工厂选择变化处理
const handleFactoryChange = (factoryId: string) => {
    drawerProps.value.row.workshopId = undefined;
    workshopList.value = [];
    if (factoryId) {
        loadWorkshopList(factoryId);
    }
};

// 监听抽屉打开状态
watch(drawerVisible, (visible) => {
    if (visible) {
        loadFactoryList();
        // 如果是编辑或查看模式，且已有工厂ID，则加载对应车间列表
        if (drawerProps.value.row.factoryId) {
            loadWorkshopList(drawerProps.value.row.factoryId);
        }
        // 设置默认状态
        if (drawerProps.value.title === '新增' && !drawerProps.value.row.status) {
            drawerProps.value.row.status = 'ENABLED';
        }
    }
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
    drawerProps.value = params;
    drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const handleSubmit = () => {
    ruleFormRef.value?.validate(async valid => {
        if (!valid) return;
        try {
            await drawerProps.value.api?.(drawerProps.value.row);
            ElMessage.success({ message: `${drawerProps.value.title}产线成功！` });
            drawerProps.value.getTableList?.();
            drawerVisible.value = false;
        } catch (error) {
            console.error(error);
        }
    });
};

// 暴露方法给父组件
defineExpose({
    acceptParams
});
</script>

<style scoped>
.el-drawer__body {
    padding: 20px;
}
</style>